package org.springframework.security.oauth2.provider;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.springframework.security.oauth2.common.util.OAuth2Utils;

@SuppressWarnings("serial")
abstract class BaseRequest implements Serializable {

    private String clientId;

    private Set<String> scope = new HashSet<String>();

    private Map<String, String> requestParameters = Collections.unmodifiableMap(new HashMap<String, String>());

    public String getClientId() {
        return clientId;
    }

    public Set<String> getScope() {
        return scope;
    }

    public Map<String, String> getRequestParameters() {
        return requestParameters;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((clientId == null) ? 0 : clientId.hashCode());
        result = prime
                * result
                + ((requestParameters == null) ? 0 : requestParameters
                .hashCode());
        result = prime * result + ((scope == null) ? 0 : scope.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        BaseRequest other = (BaseRequest) obj;
        if (clientId == null) {
            if (other.clientId != null)
                return false;
        } else if (!clientId.equals(other.clientId))
            return false;
        if (requestParameters == null) {
            if (other.requestParameters != null)
                return false;
        } else if (!requestParameters.equals(other.requestParameters))
            return false;
        if (scope == null) {
            if (other.scope != null)
                return false;
        } else if (!scope.equals(other.scope))
            return false;
        return true;
    }

    protected void setScope(Collection<String> scope) {
        if (scope != null && scope.size() == 1) {
            String value = scope.iterator().next();
            if (value.contains(" ") || value.contains(",")) {
                scope = OAuth2Utils.parseParameterList(value);
            }
        }
        this.scope = Collections.unmodifiableSet(scope == null ? new LinkedHashSet<String>() : new LinkedHashSet<String>(scope));
    }

    protected void setRequestParameters(Map<String, String> requestParameters) {
        if (requestParameters != null) {
            this.requestParameters = Collections.unmodifiableMap(new HashMap<String, String>(requestParameters));
        }
    }

    protected void setClientId(String clientId) {
        this.clientId = clientId;
    }
}
